import dingtalkim_1_0, {
  SendRobotInteractiveCardHeaders,
  SendRobotInteractiveCardRequest,
  SendRobotInteractiveCardRequestSendOptions,
} from '@alicloud/dingtalk/dist/im_1_0/client';
import Util, * as $Util from '@alicloud/tea-util';

import { DingClientService } from './client.serivce';
import { genCardId } from './utils';

interface InteractiveCardOptions {
  cardTemplateId: string;
  openConversationId?: string;
  singleChatReceiver?: string;
  cardBizId: string;
  robotCode: string;
  callbackUrl?: string;
  cardData: string;
  userIdPrivateDataMap?: string;
  unionIdPrivateDataMap?: string;
  sendOptions?: SendRobotInteractiveCardRequestSendOptions;
  pullStrategy?: boolean;
}
interface InteractiveCardHeader {
  accessToken: string;
}

interface InteractiveCardHelpOptions {
  robotCode: string;
  userId: string;
  cardBizId: string;
  cardData: Record<string, any>;
}

export class MiService extends DingClientService {
  constructor() {
    super();
  }

  protected readonly client = new dingtalkim_1_0(this.createClient());

  /** 机器人发送互动卡片（普通版）
   *
   * @link https://open.dingtalk.com/document/orgapp/robots-send-interactive-cards
   */
  protected async interactiveCard(
    options: InteractiveCardOptions,
    headers: InteractiveCardHeader,
  ): Promise<void> {
    const sendRobotInteractiveCardHeaders = new SendRobotInteractiveCardHeaders(
      { xAcsDingtalkAccessToken: headers.accessToken },
    );

    const sendOptions = new SendRobotInteractiveCardRequestSendOptions(
      options.sendOptions,
    );
    const sendRobotInteractiveCardRequest = new SendRobotInteractiveCardRequest(
      {
        cardTemplateId: options.cardTemplateId,
        openConversationId: options.openConversationId,
        singleChatReceiver: options.singleChatReceiver,
        cardBizId: options.cardBizId,
        robotCode: options.robotCode,
        callbackUrl: options.callbackUrl,
        cardData: options.cardData,
        userIdPrivateDataMap: options.userIdPrivateDataMap,
        unionIdPrivateDataMap: options.unionIdPrivateDataMap,
        sendOptions: sendOptions,
        pullStrategy: options.pullStrategy,
      },
    );
    try {
      const res = await this.client.sendRobotInteractiveCardWithOptions(
        sendRobotInteractiveCardRequest,
        sendRobotInteractiveCardHeaders,
        new $Util.RuntimeOptions({}),
      );
      if (res.statusCode !== 200) {
        throw new Error('发送卡片失败: ' + JSON.stringify(res.body));
      }
    } catch (err) {
      if (!Util.empty(err.code) && !Util.empty(err.message)) {
        throw new Error(err.message);
      } else {
        throw new Error('发送卡片失败: ' + JSON.stringify(err));
      }
    }
  }
}

export class DingMiService extends MiService {
  constructor() {
    super();
  }

  /** 发送帮助文档 */
  help(options: InteractiveCardHelpOptions, accessToken: string) {
    return this.interactiveCard(
      {
        cardTemplateId: 'StandardCard',
        cardBizId: options.cardBizId,
        cardData: JSON.stringify(options.cardData),
        robotCode: options.robotCode,
        singleChatReceiver: `{"userId":"${options.userId}"}`,
      },
      { accessToken },
    );
  }

  /** 发送固定模板卡片 */
  standardCard(
    options: {
      senderStaffId: string;
      robotCode: string;
      cardData: Record<string, any>;
    },
    accessToken: string,
  ) {
    return this.interactiveCard(
      {
        cardTemplateId: 'StandardCard',
        singleChatReceiver: `{"userId":"${options.senderStaffId}"}`,
        cardBizId: genCardId('StandardCard', options.senderStaffId),
        robotCode: options.robotCode,
        cardData: JSON.stringify(options.cardData),
      },
      { accessToken },
    );
  }
}
